#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>

//无名管道写


//捕或的信号处理
void hand(int agr)
{

	printf("已经捕获到了ctrl+c信号\n");
}



int main()
{

	char buf[64] = {0};
	char buf2[64] = {0};
	int pfd[2];
	//创建无名管道
	int ret;
	ret = pipe(pfd);
	if(ret < 0)
	{
		perror("pipe");
	}

	printf("文件描述符 = pfd[0] = %d, pfd[1]=%d\n", pfd[0], pfd[1]);


	//创建子进程
	pid_t pid;
	pid = fork();
	if( pid < 0)
	{
		perror("fork");

	}else if( pid == 0)
	{
		close(pfd[0]);
		//子进程
		int i = 0;
		while(1)
		{
			if(i == 3)
			{
				break;
			}
			strcpy(buf, "xiaoyang\n");
			write(pfd[1], buf, 64);
			sleep(1);
			i++;
		}

	}else
	{
		//父进程
		int i = 0;
		close(pfd[1]);
		while(1)
		{
			if(i == 3)
			{
				break;
			}
			int re = read(pfd[0], buf2, 64);
			if(re < 0)
			{
				perror("read");
			}
			printf("read pipe = %s", buf2);
			sleep(1);
			i++;
		}
	}


	//信号捕获
	struct sigaction act;		//定义sigaction结构体
	act.sa_handler = hand;
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);
	sigaction(SIGINT, &act,NULL); //信号捕获

	while(1)
	{
		sleep(1);
	}
	return 0;
}






